package mallindex

import (
	"context"
	// "fmt"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/utils/pointy"
	"mall/service/backend/common/utils/miniapp"
	"mall/service/backend/rpc/backendclient"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/api/internal/utils/parse"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetBannerListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetBannerListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetBannerListLogic {
	return &GetBannerListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetBannerListLogic) GetBannerList(
	req *types.GetBannerListReq,
	headers *[]*types.Header,
) (resp *types.BannerListResp, err error) {
	userId := jwt.GetUserId(l.ctx)

	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	preload := "banner:Id,Title,LinkType,LinkUrl,AdType,AdId,PicUrl"
	var filters []string
	filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	if req.Type != nil {
		filters = append(filters, "Type,equalTo:"+strconv.FormatInt(int64(*req.Type), 10))
	} else {
		filters = append(filters, "Type,equalTo:"+strconv.FormatInt(int64(globalkey.SettingBannerTypeWechatMiniIndex), 10))
	}

	res, err := l.svcCtx.BackendRpc.GetBannerList(l.ctx, &backendclient.BaseListReq{
		Offset:     uint32((page - 1) * pageSize),
		Limit:      uint32(pageSize),
		Preload:    pointy.GetPointer(preload),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(globalkey.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return nil, err
	}

	// logrus.Info(fmt.Sprintf("GetBannerList res: %+v", res))

	var hasNextPage bool
	var hasPreviousPage bool
	if res.HasNextPage != nil && *res.HasNextPage > 0 {
		hasNextPage = true
	}
	if res.HasPreviousPage != nil && *res.HasPreviousPage > 0 {
		hasPreviousPage = true
	}

	resp = &types.BannerListResp{
		BaseListInfo: types.BaseListInfo{
			HasNextPage:     hasNextPage,
			HasPreviousPage: hasPreviousPage,
		},
	}
	if len(res.List) > 0 {
		for _, v := range res.List {
			var linkUrl *string
			if v.LinkType != nil && *v.LinkType == uint32(globalkey.SettingBannerLinkTypeAbsolute) { // H5 绝对路径
				linkUrl = v.LinkUrl
			} else {
				linkUrl = pointy.GetPointer(miniapp.GetLinkUrl(v.LinkType, v.AdType, v.AdId, v.LinkUrl))
			}
			resp.List = append(resp.List, &types.BannerInfo{
				Id:        v.Id,
				Title:     v.Title,
				ImageUrl:  v.PicUrl,
				LinkToUrl: linkUrl,
			})
		}
	}

	*headers = []*types.Header{
		{
			Key:   "x-class",
			Value: "com.djx.appview.MallIndexPage",
		},
	}

	return resp, nil
}
